<?php
namespace app\common\command;

use app\common\model\index\LoginModel;
use app\common\model\index\LoginTokenModel;
use phpseclib3\Net\SSH2;
use think\admin\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;



/**
 * 例子
 *
 * @package app\store\command
 */
class StartCommand extends Command
{

    protected function configure()
    {
        $this->setName('sshToos')->setDescription('链接linux的工具服务');
        $this->addArgument('status', Argument::OPTIONAL, 'wokermen 状态命令' );
        $this->addArgument('other', Argument::OPTIONAL, 'wokermen 额外命令' );

    }
    /**
     * xml订单入表并推送报关
     * @param Input $input
     * @param Output $output
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {

        $default = '';
        // 注意：这里与上个例子不同，使用的是websocket协议
        $ws_worker = new Worker("websocket://127.0.0.1:2345");

        // 启动4个进程对外提供服务
        $ws_worker->count = 4;

        //
        /*$ws_worker->onWorkerStart = function(Worker $worker)
        {
            $worker->connections->getRemoteIp
        };*/

        $ws_worker->onConnect = function(TcpConnection $connection)
        {
            $ip = $connection->getRemoteIp();
            $flag = md5($ip);

            // 查询数据库 找到对应的 服务器链接
            $login_tokens = LoginTokenModel::mk()->where('flag', $flag)->select();

            $login_tokens->each(function ($item) use(&$token_arr) {
                 $token_arr[$item->user_id] =  $item->token;
            });

            $service_data = LoginModel::whereIn('id', array_keys($token_arr))->select()->toArray();

            $cache_data = [];
            foreach ($service_data as $item) {

                $cache_data[$token_arr[$item['id']]] = $item;
            }

            Cache::set($flag, json_encode($cache_data));
        };

        // 当收到客户端发来的数据后返回hello $data给客户端
       $ws_worker->onMessage = function(TcpConnection $connection, $data)
        {

            [$token, $command ] = json_decode($data, true);

            /*if () {

            }*/

            // 或者捕获异常
            /*try {
               $ssh = $this->login();
               echo $ssh;
               $output = '456';
               //$output = $ssh->exec('ls -la');

           } catch (\Exception $e) {

               echo "连接可能已经断开: " . $e->getMessage() . "\n";
               $output =  "连接可能已经断开: " . $e->getMessage() . "\n";
           }

           $connection->send($output);*/

            /*$arr = [];
            foreach ($connection->worker->connections as $connect) {
                $arr[] = $connect->id;
            }
            $json_str = json_encode($arr);
            $connection->send($json_str."({$connection->id})");*/

            /*$cache_data = Cache::get('aa'.$connection->id);

            if ($cache_data) {
                $cache_data = json_decode($cache_data, true);
            }
            $cache_data[]   = $data;

            // 存储命令
            Cache::set('aa'.$connection->id, json_encode($cache_data));

            $connection->send(json_encode($cache_data));*/

            /*$cmd = ['ls', 'll'];
            // 判断是否为shell命令
            if ( in_array($cmd)) {

            }
            // 向客户端发送hello $data
            $connection->send($data);*/
        };

        // 运行worker
        Worker::runAll();
        die;

        /*// 创建一个Worker监听2345端口，使用http协议通讯
        $http_worker = new Worker("http://127.0.0.1:2345");
        // 启动4个进程对外提供服务
        $http_worker->count = 4;

        // 接收到浏览器发送的数据时回复hello world给浏览器
        $http_worker->onMessage = function(TcpConnection $connection, Request $request)
        {
            $str = $request->queryString();
            // 向浏览器发送hello world
            $connection->send($str);
        };

        // 运行worker
        Worker::runAll();*/


    }



    public function login ()
    {
        return 1;
        $ssh = new SSH2('8.135.41.209');
        if (!$ssh->login('root', '(Awrsyywn5241151)')) {
            exit('登录失败');
        }

        return $ssh;
    }
}

?>